<template>
  <div class="inventory-reports">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>库存报表</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport" :disabled="!activeTab">
              <el-icon><Download /></el-icon>
              导出报表
            </el-button>
            <el-button type="primary" @click="handlePrint">
              <el-icon><Printer /></el-icon>
              打印报表
            </el-button>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><RefreshRight /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 报表类型选项卡 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane name="status" label="库存状态报表">
          <inventory-status-report 
            ref="statusReport" 
            @loading-change="handleLoadingChange" 
          />
        </el-tab-pane>
        <el-tab-pane name="movement" label="库存流水报表">
          <inventory-movement-report 
            ref="movementReport" 
            @loading-change="handleLoadingChange" 
          />
        </el-tab-pane>
        <el-tab-pane name="value" label="库存价值报表">
          <inventory-value-report 
            ref="valueReport" 
            @loading-change="handleLoadingChange" 
          />
        </el-tab-pane>
        <el-tab-pane name="turnover" label="库存周转率报表">
          <inventory-turnover-report 
            ref="turnoverReport" 
            @loading-change="handleLoadingChange" 
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, provide, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import InventoryStatusReport from './report-components/InventoryStatusReport.vue';
import InventoryMovementReport from './report-components/InventoryMovementReport.vue';
import InventoryValueReport from './report-components/InventoryValueReport.vue';
import InventoryTurnoverReport from './report-components/InventoryTurnoverReport.vue';
import { exportInventoryReport } from '@/api/inventory';

export default {
  name: 'InventoryReports',
  components: {
    InventoryStatusReport,
    InventoryMovementReport,
    InventoryValueReport,
    InventoryTurnoverReport
  },
  setup() {
    const activeTab = ref('status');
    const loading = ref(false);
    
    // 报表组件引用
    const statusReport = ref(null);
    const movementReport = ref(null);
    const valueReport = ref(null);
    const turnoverReport = ref(null);
    
    // 提供loading状态给子组件
    provide('loading', loading);
    
    // 处理选项卡切换
    const handleTabChange = (tab) => {
      activeTab.value = tab.paneName;
      
      // 切换选项卡时自动刷新该报表数据
      refreshCurrentReport();
    };
    
    // 处理子组件loading状态变化
    const handleLoadingChange = (isLoading) => {
      loading.value = isLoading;
    };
    
    // 刷新当前报表数据
    const refreshCurrentReport = () => {
      const reportRefs = {
        status: statusReport,
        movement: movementReport,
        value: valueReport,
        turnover: turnoverReport
      };
      
      const currentRef = reportRefs[activeTab.value];
      if (currentRef.value && typeof currentRef.value.fetchData === 'function') {
        currentRef.value.fetchData();
      }
    };
    
    // 刷新按钮事件处理
    const handleRefresh = () => {
      refreshCurrentReport();
    };
    
    // 导出报表
    const handleExport = async () => {
      const loadingInstance = ElLoading.service({
        text: '导出中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 获取当前报表的过滤条件
        const reportRefs = {
          status: statusReport,
          movement: movementReport,
          value: valueReport,
          turnover: turnoverReport
        };
        
        const currentRef = reportRefs[activeTab.value];
        const params = currentRef.value ? currentRef.value.getExportParams() : {};
        
        // 调用导出API
        const response = await exportInventoryReport(activeTab.value, params);
        
        // 处理文件下载
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `库存${getReportName(activeTab.value)}报表_${new Date().toISOString().slice(0, 10)}.xlsx`;
        link.click();
        URL.revokeObjectURL(link.href);
        
        ElMessage.success('报表导出成功');
      } catch (error) {
        console.error('导出报表失败:', error);
        ElMessage.error('报表导出失败');
      } finally {
        loadingInstance.close();
      }
    };
    
    // 打印报表
    const handlePrint = () => {
      window.print();
    };
    
    // 获取报表中文名称
    const getReportName = (type) => {
      const names = {
        status: '状态',
        movement: '流水',
        value: '价值',
        turnover: '周转率'
      };
      return names[type] || '';
    };
    
    onMounted(() => {
      // 初始加载默认选项卡数据
      refreshCurrentReport();
    });
    
    return {
      activeTab,
      loading,
      statusReport,
      movementReport,
      valueReport,
      turnoverReport,
      handleTabChange,
      handleLoadingChange,
      handleRefresh,
      handleExport,
      handlePrint
    };
  }
};
</script>

<style scoped>
.inventory-reports {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

@media print {
  .el-card__header,
  .header-actions,
  .el-tabs__header {
    display: none !important;
  }
  
  .el-card {
    box-shadow: none !important;
    border: none !important;
  }
  
  .el-tabs__content {
    padding: 0 !important;
  }
}
</style> 